'''
Created on Jun 1, 2009

@author: mkiyer
'''

import os
import sys
import logging

from veggie.app.chipseq import sw_root
from veggie.app.application import CommandLineApplication

class HPeak(CommandLineApplication):
    '''
    application controller for the HPeak program

    See HPeak documentation at:
    http://www.sph.umich.edu/csg/qin/HPeak/
    '''
    _executable = "perl " + os.path.join(sw_root, 'HPeak-2.2', 'HPeak.pl')

    def get_result_paths(self):
        outfile = '.'.join([self._options['-n'], 'hpeak', 'out'])
        return [outfile]

    def run(self, t_file, c_file, format='BED', name="hpeak", 
            options=None, args=None, cwd=None):
        if cwd:
            self.cwd = cwd
        if options:
            self.addOptions(options)
        if args:
            self.args_set(args)

        # default args for hpeak
        self.addOption('-format', 'BED')
        # experiment name
        self.addOption('-n', name)

        # treatment
        t_inp_path = os.path.join(os.path.abspath(self.cwd), name + '.treatment.inp')        
        t_inp_fhd = open(t_inp_path, 'w')
        t_inp_fhd.write('%s\n' % (t_file))
        t_inp_fhd.close()
        # add option for treatment name
        self.addOption('-t', t_inp_path)
        # if control is present setup control data
        if c_file is not None:
            c_inp_path = os.path.join(os.path.abspath(self.cwd), name + '.control.inp')
            # control
            c_inp_fhd = open(c_inp_path, 'w')
            c_inp_fhd.write(c_file + '\n')
            c_inp_fhd.close()
            # add control to options
            self.addOption('-c', c_inp_path)
        # add user-defined options (these may override the defaults)
        if options:
            self.addOptions(options)
        # output command line to file
        logging.debug("Command line: %s" % (self.getCommandLine()))
        return self()

        